package com.yl.controller;

import com.yl.common.constant.CommonConstant;
import com.yl.common.result.Result;
import com.yl.common.utils.JwtUtil;
import com.yl.common.utils.PasswordUtil;
import com.yl.common.utils.RedisUtil;
import com.yl.modules.system.dto.LoginUser;
import com.yl.modules.system.entity.SysUser;
import com.yl.modules.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author yl
 * @description
 * @date 2021/09/24 10:30
 */
@Api(tags = "用户")
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    ISysUserService userService;
    @Autowired
    RedisUtil redisUtil;

    @ApiOperation("登录接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(
            @RequestParam(name = "username") String username,
            @RequestParam(name = "password") String password) {
        SysUser user = userService.queryByUsername(username);
        if (user == null) {
            return Result.error("用户不存在或已注销");
        }
        String userpassword = PasswordUtil.encrypt(username, password, user.getSalt());
        String syspassword = user.getPassword();
        if (!syspassword.equals(userpassword)) {
            return Result.error("密码错误");
        }
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        return Result.OK("登录成功", user);
    }

    @ApiOperation("注册用户")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(SysUser sysUser) {
        sysUser.setId(UUID.randomUUID().toString());
        SysUser user = userService.queryByUsername(sysUser.getUsername());
        if (user != null) {
            return Result.error("用户已存在");
        }
        String salt = PasswordUtil.randomGen(8);
        sysUser.setSalt(salt);
        userService.save(sysUser);
        return Result.OK("注册成功！");
    }
    @ApiOperation("查询登录人员资料")
    @RequestMapping(value = "/queryByToken", method = RequestMethod.POST)
    public Result queryByToken(HttpServletRequest request) {
        String userNameByToken = JwtUtil.getUserNameByToken(request);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.OK(sysUser);
    }
}
